package com.zhongge.jdbc;

import java.sql.*;
import java.util.ArrayList;

/**
 * @ClassName JdbcTest 初识JDBC
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
public class JdbcTest {
    public static void main(String[] args) {
        //使用数据结构便于将读取到的数据存储在数据结构中
        ArrayList<Book> arrayList = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //创建驱动
            Driver driver = new com.mysql.cj.jdbc.Driver();
            //注册驱动
            DriverManager.registerDriver(driver);

            //创建连接

            //路径
            String url = "jdbc:mysql://localhost:3306/tushu";
            //用户名
            String name = "root";
            //密码
            String password = "123456";
            connection = DriverManager.getConnection(url, name, password);

            //创建语句对象将sql语句带过去
            statement = connection.createStatement();

            //执行sql代码
            String sql = "select * from book";
            statement.executeQuery(sql);

            //处理结果
            resultSet = statement.getResultSet();
            while (resultSet.next()) {
                String name1 = resultSet.getString("name");
                int price = resultSet.getInt("price");
                String author = resultSet.getString("author");
                String type = resultSet.getString(4);
                boolean isBorrow = resultSet.getBoolean(5);

                Book book = new Book(name1, price, author, type);
                arrayList.add(book);
            }
            System.out.println(arrayList);

            String sql1 = "INSERT INTO book (NAME, price, author, TYPE, isBorrow)\n" +
                    "VALUES ('三体', 68, '刘慈欣', '科幻', FALSE)";
            statement.executeUpdate(sql1);
        } catch (SQLException e) {
           e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
